<template>
    <div>
        <Modal :title="modalTitle" v-model="modalShow" :width="modalWidth" :mask-closable="false" :closable="false">
            <div v-show="modalType === 'edit' || modalType === 'add'">
                <Form ref="formItem" :rules="ruleValidate" label-position="top" :model="formItem">
                    <!--<FormItem label="类别：" prop="category_id">
                        <Select v-model="formItem.category_id" placeholder="请选择类别" filterable>
                            <Option v-for="(option, index) in categoryObj" :value="option.id" :key="index">{{option.category}}</Option>
                        </Select>
                    </FormItem>-->
                    <Alert>基本信息</Alert>
                    <Row :gutter="16" >
                        <Col span="12">
                            <FormItem prop="name" label="姓名:">
                                <Input v-model="formItem.name" placeholder="请输入人员姓名"/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem prop="sex" label="性别:">
                                <RadioGroup v-model="formItem.sex">
                                    <Radio label="0" border>男</Radio>
                                    <Radio label="1" border>女</Radio>
                                </RadioGroup>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem prop="nation" label="民族:">
                                <Input v-model="formItem.nation" maxlength="20" placeholder="请输入民族" />
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem prop="idcard" label="身份证号:">
                                <Input v-model="formItem.idcard" placeholder="请输入身份证号"/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem prop="tui_xiu_date" label="退休时间:">
                                <DatePicker format="yyyy年" type="year" v-model="formItem.tui_xiu_date"
                                            :editable="false"
                                            :options="endTimeOptions" placeholder="请选择退休时间">
                                </DatePicker>
                            </FormItem>
                        </Col>
                        <!--<Col span="12">
                            <FormItem prop="record_number" label="全宗号:">
                                <Input v-model="formItem.record_number" placeholder="请输入全宗号"/>
                            </FormItem>
                        </Col>-->
                        <Col span="12">
                            <FormItem prop="serial_number" label="流水号:">
                                <Input :disabled="serialNumDisabled" v-model="formItem.serial_number" placeholder="请输入流水号"/>
                            </FormItem>
                        </Col>
                        <!--<Col span="12">
                            <FormItem prop="work_name" label="单位名称:" >
                                <Input v-model="formItem.work_name" placeholder="请输入单位名称"/>
                            </FormItem>
                        </Col>-->
                        <Col span="12">
                            <FormItem label="养老保险编号:" prop="yang_lao_no">
                                <Input v-model="formItem.yang_lao_no" placeholder="请输入单位养老保险编号"/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="单位所属社保分中心:" prop="she_bao_zhong_xin">
                                <Input v-model="formItem.she_bao_zhong_xin" placeholder="请输入单位所属社保分中心"/>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="单位社会保险隶属关系:" prop="li_shu_guan_xi">
                                <Select v-model="formItem.li_shu_guan_xi">
                                    <Option value="1"> 市保</Option>
                                    <Option value="2"> 省保（中直）</Option>
                                    <Option value="3"> 省保（省直）</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col span="12">
                            <FormItem label="总页数:" prop="img_total">
                                <Input v-model="formItem.img_total" placeholder="请输入总页数"/>
                            </FormItem>
                        </Col>
                        <Col span="24">
                            <FormItem label="附加材料:" prop="img_explain">
                                <wl-upload-oss-files
                                        v-model="imgList"
                                        :maxNum="4"
                                        uploadType="hadoop"
                                        @result="resultAction"
                                        fileDir="remark"
                                        fileName="md5"
                                        :uploadUrl="getUploadUrl"
                                        :format="format">
                                </wl-upload-oss-files>
                            </FormItem>
                        </Col>
                        <Col span="24">
                            <FormItem label="备注信息:" prop="remark">
                                <Input v-model="formItem.remark" type="textarea" placeholder="请输入备注信息"/>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div v-show="modalType === 'info'">
                <Form label-position="right" :model="formItem" :label-width="150">
                    <Alert>基本信息</Alert>
                    <FormItem label="审核状态：">
                        {{formItem.state === '0' ? '待审核' : '审核通过'}}
                    </FormItem>
                </Form>
            </div>
            <div slot="footer">
                <template v-if="modalType === 'edit' || modalType === 'add'">
                    <Button type="text" @click="cancelOption">取消</Button>
                    <Button type="success" @click="saveOption" :loading="btnLoading">保存</Button>
                </template>
                <template v-if="modalType === 'info'">
                    <Button type="text" @click="cancelOption">关闭</Button>
                </template>
            </div>
        </Modal>
    </div>
</template>

<script>
import { saveAndUpdateUser, getPersonalMaterialList, getCardNo } from '@/api/record'
import { identityCodeValid } from '@/libs/tools'

export default {
  name: 'OptionModal',
  props: {
    modalTitle: {
      type: String,
      default: () => {
        return ''
      }
    },
    modalType: {
      type: String,
      default: () => {
        return 'info'
      }
    },
    modalShow: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    modalWidth: {
      type: Number,
      default: () => {
        return 800
      }
    },
    dataObj: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    const validateIdcard = (rule, value, callback) => {
      const obj = identityCodeValid(value)
      if (!obj.pass) {
        this.selectIdCard(value, callback)
      } else {
        callback()
      }
    }
    const validateDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择退休时间'))
      } else {
        callback()
      }
    }
    const validateImg = (rule, value, callback) => {
      const reg = /^[1-9]\d*$/
      if (!value) {
        callback(new Error('总页数不能为空'))
      } else if (!reg.test(value)) {
        callback(new Error('请检查格式'))
      } else {
        callback()
      }
    }
    return {
      endTimeOptions: {
        disabledDate: date => {
          return date && date.valueOf() > Date.now()
        }
      },
      ruleValidate: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        nation: [
          { required: true, message: '请输入民族', trigger: 'blur' }
        ],
        /* record_number: [
          { required: true, message: '全宗号不能为空', trigger: 'blur' }
        ], */
        serial_number: [
          { required: true, message: '流水号不能为空', trigger: 'blur' }
        ],
        idcard: [
          { required: true, validator: validateIdcard, trigger: 'blur' }
        ],
        tui_xiu_date: [
          { required: true, validator: validateDate, trigger: 'blur' }
        ],
        img_total: [
          { required: true, validator: validateImg, trigger: 'blur' }
        ]
      },
      btnLoading: false,
      serialNumDisabled: false,
      formItem: {},
      categoryObj: {},
      format: ['jpg', 'jpeg', 'png'],
      imgList: ''
    }
  },
  methods: {
    selectIdCard (value, callback) {
      let param = { idcard: value, name: this.formItem.name }
      getCardNo(param).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          if (data.data === 1) {
            callback()
          } else {
            callback(new Error('证件号不正确'))
          }
        } else {
          this.error(data)
        }
      })
    },
    cancelOption () {
      this.$emit('cancelOption')
    },
    saveOption () {
      if (!this.$common.xeUtils.isEmpty(this.imgList)) {
        let dataList = this.$common.xeUtils.clone(this.imgList)
        dataList = dataList.substr(0, dataList.length - 1)
        dataList = dataList.split(',')
        this.formItem.img_explain = []
        dataList.forEach(item => {
          this.formItem.img_explain.push(item)
        })
        this.formItem.img_explain = this.formItem.img_explain.join(',')
      }
      this.formItem.tui_xiu_date = this.formItem.tui_xiu_date ? this.$common.xeUtils.toDateString(this.formItem.tui_xiu_date, 'yyyy') : ''
      let param = {}
      if (this.modalType === 'add') {
        param = this.formItem
        this.$delete(param, 'id')
      } else if (this.modalType === 'edit') {
        param = {
          ...this.formItem,
          type: 'edit'
        }
      }
      this.$refs['formItem'].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          saveAndUpdateUser(param).then(ret => {
            let data = ret.data
            if (data.errcode === 0) {
              this.btnLoading = false
              this.success()
              this.$emit('saveOption')
            } else {
              this.btnLoading = false
              this.error(data)
            }
          })
        } else {
          this.$Message.error({
            content: '操作失败,请核对添加信息后重试'
          })
        }
      })
    },
    resultAction () {},
    success (val) {
      val = this.$common.xeUtils.isEmpty(val) ? '操作成功' : val
      this.$Message.success(val)
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    getPersonalMaterialListAction () {
      const param = { archive_id: this.formItem.id, pageNo: 1, pageSize: 10, totalRecord: 0 }
      getPersonalMaterialList(param).then(res => {
        if (res.data.errcode === 0) {
          const data = res.data.data
          this.serialNumDisabled = data.length > 0
        }
      })
    }
  },
  mounted () {
  },
  watch: {
    dataObj (val) {
      this.formItem = val
      if (!this.$common.xeUtils.isEmpty(val.img_explain)) {
        this.imgList = val.img_explain
      }
    },
    'dataObj.id' (val) {
      if (val && this.modalType === 'edit') {
        this.getPersonalMaterialListAction()
      } else {
        this.serialNumDisabled = false
      }
    }
  },
  computed: {
    getUploadUrl () {
      return this.$config.upLoadFileUrl
    }
  }
}
</script>

<style scoped>
    /deep/ .ivu-alert-info {
        border: 1px solid #EDEFF0;
        background-color: #F8F8F9;
    }
</style>
